package com.wang.tool.idem.aop;

import com.wang.tool.idem.IdemServer;
import com.wang.tool.lock.LockServer;
import com.wang.tool.util.CommonUtil;
import com.wang.tool.util.SimpleLogUtil;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.ProxyMethodInvocation;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author wangshaopeng
 * @Date 2022/5/10
 */
public class IdemConfiguration {

    @Bean("idemAdvisor1")
    @ConditionalOnMissingBean(name = "idemAdvisor1")
    public Advisor idemAdvisor1(@Autowired IdemAdvisorOrder order, @Autowired IdemServer idemServer, @Autowired IdemKeyBuilder keyBuilder) {
        IdemAdvice cacheAdvice = new IdemAdvice(idemServer,keyBuilder);
        Advice advice = (MethodInterceptor) invocation -> cacheAdvice.idemAround(new MethodInvocationProceedingJoinPoint((ProxyMethodInvocation) invocation));
        AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
        String expression =
                //方法/类注解
                "@annotation(" + Idem.class.getName() + ")"
                        //public
                        + " && execution(public * *(..))"
                        //非Object自带函数
                        + " && !execution(public java.lang.String toString())"
                        + " && !execution(public int hashCode())"
                        + " && !execution(public boolean equals(java.lang.Object))";
        advisor.setExpression(expression);
        advisor.setOrder(order.getOrder());
        advisor.setAdvice(advice);
        SimpleLogUtil.info("[{0}IsAvailable] order:{1}, expression:{2}", Idem.class.getName(), order.getOrder(), expression);
        return advisor;
    }

}
